<template>
  <div class="all" v-if="curData">
    <!-- 指标/形态提醒 -->
    <scroller class="scroller" ref="scroller" resize="none">

      <div class="wrapper">
        <!-- 标的 -->
        <text class="font28 text3 mb20 padding">{{T('标的')}}</text>
        <div class="search bg2 mb40 ml40 mr40" @click="searchClick">
          <text
            :class="['font30','all', pair.length > 0 ? 'text2' : 'text3']">{{ pair.length > 0 ? counterCoinShort :T('请选择币种')}}</text>
          <LImage v-if="pageRef != 'edit'" class="search-image" :src="Config.img('xiala.png')"></LImage>
        </div>
        <!-- 触发条件 -->
        <div v-for="(item, index) in conditionList" :key="index">
          <text class="font28 text3 mb20 ml40">{{ item.type == 'timeInterval' ? T('周期'):T('阀值') }}</text>
          <div class="sub-item-wrap">
            <div :class="['bg2','height80','sub-item', item.value == subItem ? 'sub-item-sel':'sub-item-nor']"
              v-for="(subItem, subIndex) in item.values" :key="subIndex" @click="onCondition(item,subItem)">
              <text
                :class="['font30',item.value == subItem ? 'main-t1' :'text3' ]">{{ conditionTransform(item.type,subItem) }}</text>
            </div>
          </div>
        </div>
        <!-- 预警频率 -->
        <text class="font28 text3 mb20 padding">{{T('预警频率')}}</text>
        <VConditionCell class="ml40 mr40" :title="frequency.name" @onConditionClick="onConditionClick"
          type="yjFrequency" />
        <div class="height20" />
        <!-- 到期时间 -->
        <text class="font28 text3 mb20 padding">{{T('到期时间')}}</text>
        <VConditionCell class="ml40 mr40" :title="expirationTime || T('请选择到期时间')"
          :isGrayText="expirationTime && expirationTime.length > 0" @onConditionClick="onConditionClick"
          type="pickerTime" />
        <div class="height20" />

        <!-- 预警方式 -->
        <text class="font28 text3 mb20 padding">{{T('预警方式')}}</text>
        <VCheck class="mb40 padding" :menus="alertTypes" :selTypes="selAlertTypes" @checkClick="onAlertTypeSel" />

      </div>
    </scroller>

    <div class="bottom">
      <div class="but main1" @click="onSave">
        <text class="font36 text1">{{T('添加预警')}}</text>
      </div>
    </div>

    <x-coin type="pair" :pair="pair" v-if="showPair" :show="showPair" @overlayClick="pairHide"
      @onPairClick="onPairSel" />
    <x-picker type="date" v-if="showPicker" :show="showPicker" :curDate="expirationTime || curDate"
      @overlayClick="timePickerHide" @timePickerResult="timePickerResult" />
  </div>
</template>

<style src="@/_css/style.css" ></style>
<style scoped>
  .scroller {
    display: flex;
    flex-direction: column;
    flex: 1;
  }
  .refresh {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    width: 750px;
    height: 80px;
  }
  .wrapper {
    margin-top: 30px;
    display: flex;
    flex-direction: column;
  }
  .padding {
    padding: 0 40px;
  }
  .search {
    flex-direction: row;
    align-items: center;
    height: 81px;
    padding-left: 28px;
    padding-right: 30px;
    border-color: #252a4d;
    border-radius: 4px;
    border-width: 1px;
  }
  .search-image {
    width: 20px;
    height: 16px;
  }
  .center-img {
    width: 690px;
    height: 640px;
    margin-top: 10px;
  }
  .sub-item-wrap {
    flex-direction: row;
    flex-wrap: wrap;
    margin-bottom: 24px;
    padding: 0 27px;
  }

  .sub-item {
    align-items: center;
    justify-content: center;
    width: 322px;
    margin: 0 13px;
    margin-bottom: 24px;
  }
  .sub-item-sel {
    border-color: #1677fe;
    border-width: 1px;
    border-radius: 4px;
  }
  .sub-item-nor {
    border-color: #151a2a;
    border-width: 1px;
    border-radius: 4px;
  }
  .bottom {
    height: 140px;
    flex-direction: column;
    margin-bottom: 40px;
  }
  .but {
    align-items: center;
    justify-content: center;
    margin: 20px 30px;
    height: 88px;
    border-radius: 16px;
  }
</style>

<script>
  import XPicker from "@/aide/picker/index.vue";
  import XCoin from "@/aide/coin/targetCoin.vue";
  import VConditionCell from "@/aide/view/VConditionCell.vue";
  import VCheck from "@/aide/view/VCheck.vue";
  import dateUtils from "@/aide/picker/dateutils.js";
  import jconfig from "@/_js/config";
  import jbroadcast from "@/_js/broadcast";
  import jmodal from "@/_js/modal";
  import jdebug from "@/_js/debug";
  import jhttps from "@/_js/https";
  import jtime from "@/_js/time";
  import jnavigator from "@/_js/navigator";
  const clipboard = weex.requireModule("clipboard");
  const animation = weex.requireModule("animation"); //动画
  const domModule = weex.requireModule("dom");
  const stream = weex.requireModule("stream"); //网络请求
  const weexFunction = weex.requireModule("WeexFunction");
  import I18N from "@/_i18n/i18n";
  var T = I18N.t;

  export default {
    components: {
      VConditionCell,
      VCheck,
      XPicker,
      XCoin,
    },

    data() {
      return {
        Config: jconfig,
        T: T,
        pageRef: "", //1.add 2.create 3.edit
        id: null,
        indicatorId: null,
        type: "liquidation",
        curData: null,
        //筛选的数据
        dataList: [],
        //标的
        pair: "BTCUSDT",
        exchangeName: "BINANCE",
        counterCoinShort: "BTC",
        showPair: false,
        //触发条件
        conditionList: [],
        //预警频率
        frequency: {},
        frequencyList: [
          {
            name: T("仅一次"),
            type: "once",
          },
          {
            name: T("每分钟一次"),
            type: "oncePerMinute",
          },
        ],
        //到期时间
        showPicker: false,
        curDate: null,
        expirationTime: null,
        //预警方式
        alertTypes: [
          {
            name: T("APP提醒"),
            type: "app",
          },
          {
            name: T("Telegram提醒"),
            type: "tg",
          },

          {
            name: T("电话提醒"),
            type: "phone",
          },
        ],
        selAlertTypes: [],
      };
    },

    created() {
      this.pageRef = jnavigator.getParam("pageRef");
      this.id = jnavigator.getParam("id");
      this.indicatorId = jnavigator.getParam("indicatorId");
      weexFunction.setTitle(T("爆仓提醒"));
      let isIos = weex.config.env.platform.toUpperCase() != "ANDROID";
      if (!isIos) {
        this.alertTypes = [
          {
            name: T("Telegram提醒"),
            type: "tg",
          },
          {
            name: T("电话提醒"),
            type: "phone",
          },
        ];
      }
    },

    mounted() {
      this.frequency = this.frequencyList[0];
      this.curDate = this.getCurrentFormattedDate();
      this.httpLoadData();
    },

    methods: {
      /********************************** HTTPS*/
      httpLoadData() {
        if (this.pageRef == "create") {
          jmodal.showLoad();
          var param = {
            indicatorType: this.type,
          };
          jhttps.post("indicator/getIndicatorInfoList", param, true, (data) => {
            jmodal.hideLoad();
            if (data.status == 200) {
              let dataList = data.data;
              if (dataList.length > 0) {
                this.curData = dataList[0];
                this.dealWithCondition();
              }
            } else {
              jmodal.toast(data.msg);
            }
          });
        } else {
          jmodal.toast(T("失败"));
          setTimeout(() => {
            jnavigator.back();
          }, 1000);
        }
      },
      dealWithCondition() {
        let timeIntervals = [];
        for (let i = 0; i < this.curData.triggerCondition.length; i++) {
          let item = this.curData.triggerCondition[i];
          timeIntervals.push(item.timeInterval)
        }
        let thresholds = this.curData.triggerCondition[0]['threshold']
        this.conditionList = [
          {
            type: "timeInterval",
            values: timeIntervals,
            value: timeIntervals[0]
          },
          {
            type: "threshold",
            values: thresholds,
            value: thresholds[0]
          },
        ];
      },
      /********************************** 点击*/
      //选择标的
      searchClick() {
        if (this.pageRef == "edit") {
          return;
        }
        this.showPair = true;
      },
      onPairSel(item) {
        this.pair = item.pair;
        this.counterCoinShort = item.counterCoinShort;
        this.exchangeName = item.exchangeName;
      },
      pairHide() {
        setTimeout(() => {
          this.showPair = false;
        }, 200);
      },
      //条件点击
      onCondition(item, subItem) {
        item.value = subItem;
        if (item.type == "timeInterval") {
          let timeIntervals = this.conditionList[0].values
          let index = timeIntervals.indexOf(subItem);
          let values = this.curData.triggerCondition[index]['threshold']
          this.conditionList[1].values = values
          this.conditionList[1].value = values[0]
        }
      },
      //条件点击
      onConditionClick(data) {
        if (data.type == "yjFrequency") {
          //切换频率
          let names = [];
          for (let i = 0; i < this.frequencyList.length; i++) {
            let item = this.frequencyList[i];
            names.push(item.name);
          }
          jmodal.actionSheet(names, this.frequency.name, (value) => {
            let index = names.indexOf(value);
            this.frequency = this.frequencyList[index];
          });
        } else if (data.type == "pickerTime") {
          //时间选择器
          this.showPicker = true;
        }
      },

      /********************************** 时间选择器*/
      //时间选择器隐藏
      timePickerHide() {
        setTimeout(() => {
          this.showPicker = false;
        }, 200);
      },
      //时间选择器结果
      timePickerResult(dateTime) {
        this.expirationTime = dateTime;
      },

      /********************************** 预警方式*/
      onAlertTypeSel(item) {
        let index = this.selAlertTypes.indexOf(item.type);
        if (index == -1) {
          this.selAlertTypes.push(item.type);
        } else {
          this.selAlertTypes.splice(index, 1);
        }
      },
      /********************************** 最终保存*/

      onSave() {
        // //触发条件
        if (this.pair.length <= 0) {
          jmodal.toast(T("请选择币种"));
          return;
        }
         if (!this.expirationTime || this.expirationTime.length <= 0) {
          jmodal.toast(T("请选择到期时间"));
          return;
        }
        jmodal.showLoad();
        const date = dateUtils.createDate(this.expirationTime);
        let param = {
          indicatorId: parseInt(this.curData.id),
          pair: this.pair,
          frequency: this.frequency.type,
          expirationTime: date.getTime(),
        };
        //触发条件
        let triggerCondition = {};
        if (this.conditionList.length > 0) {
          for (let i = 0; i < this.conditionList.length; i++) {
            let item = this.conditionList[i];
            triggerCondition[item.type] = item.value;
          }
        }
        param.triggerCondition = JSON.stringify(triggerCondition);
        //预警方式
        if (this.selAlertTypes.includes("app")) {
          param.appNotification = true;
        } else {
          param.appNotification = false;
        }
        if (this.selAlertTypes.includes("tg")) {
          param.tgNotification = true;
        } else {
          param.tgNotification = false;
        }
        if (this.selAlertTypes.includes("phone")) {
          param.phNotification = true;
        } else {
          param.phNotification = false;
        }
        if (this.pageRef == "edit") {
          param.id = parseInt(this.id);
          jhttps.postX("indicator/updateUserIndicator", param, true, (data) => {
            jmodal.hideLoad();
            if (data.status == 200) {
              jmodal.toast(T("保存成功"));
              jbroadcast.send("liquidationRefresh");
              jnavigator.back();
            } else {
              jmodal.toast(data.msg);
            }
          });
        } else {
          jhttps.postX("indicator/createUserIndicator", param, true, (data) => {
            jmodal.hideLoad();
            if (data.status == 200) {
              jmodal.toast(T("保存成功"));
              jbroadcast.send("liquidationRefresh");
              jnavigator.back();
            } else {
              jmodal.toast(data.msg);
            }
          });
        }
      },

      /********************************** 其他*/
      //获取当前时间
      //格式化为 YYYY-MM-DD HH:mm:ss
      getCurrentFormattedDate() {
        const now = new Date();
        const year = now.getFullYear(); // 获取年份
        const month = (now.getMonth() + 1).toString().padStart(2, "0"); // 获取月份（0-11），并补零
        const day = now.getDate().toString().padStart(2, "0"); // 获取日期，并补零
        const hours = now.getHours().toString().padStart(2, "0"); // 获取小时，并补零
        const minutes = now.getMinutes().toString().padStart(2, "0"); // 获取分钟，并补零
        const seconds = now.getSeconds().toString().padStart(2, "0"); // 获取秒数，并补零
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      conditionTransform(type, value) {
        if (type == "timeInterval") {
          let minutes = Number(value);
          if (minutes < 60) {
            return `${minutes}${T("分钟")}`;
          } else {
            const hours = Math.floor(minutes / 60); // 计算小时
            const remainingMinutes = minutes % 60; // 计算剩余分钟
            if (remainingMinutes === 0) {
              return `${hours}${T("小时")}`; // 如果没有剩余分钟，只显示小时
            } else {
              return `${hours}${T("小时")}${remainingMinutes}${T("分钟")}`; // 显示小时和分钟
            }
          }
        } else {
          let price = Number(value);
          return price / 1000000 + "M";
          // if (price >= 500000 && price < 2000000) {
          //   return ">=50" + T("万");
          // } else if (price >= 2000000 && price < 5000000) {
          //   return ">=200" + T("万");
          // } else if (price >= 5000000 && price < 10000000) {
          //   return ">=500" + T("万");
          // } else {
          //   return ">=1000" + T("万");
          // }
          // return value;
        }
      },
    },
  };
</script>